package dq.thread;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Dang Qi
 * @Date: 2021/4/1  15:47
 * @Description:
 */
public class NIOServer {
    public static void main(String[] args) throws IOException, InterruptedException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        List<SocketChannel> list = new ArrayList<>();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        serverSocketChannel.bind(new InetSocketAddress(9876));

        // 设置为非阻塞
        serverSocketChannel.configureBlocking(false);

        while (true) {
            Selector selector = Selector.open();
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel == null) {
                System.out.println("当前链接数量 "+list.size());
                System.out.println("--没人连接--");
                Thread.sleep(1000);
                for (SocketChannel channel : list) {
                    int k =  channel.read(byteBuffer);
                    System.out.println(k);

                    if (k != 0) {
                        // 有人发数据
                        byteBuffer.flip();
                        System.out.println("========no conn=======》" + new String(byteBuffer.array()));
                        byteBuffer.clear();
                        byteBuffer.put("处理中".getBytes());
                        channel.write(byteBuffer);
                    }
                }
            } else {
                System.out.println("--有人连接--");
                socketChannel.configureBlocking(false);
                list.add(socketChannel);

                // 得到套接字，循环所以的套接字，通过套接字获取数据
                for (SocketChannel channel : list) {
                    int k = channel.read(byteBuffer);
                    if (k != 0) {
                        byteBuffer.flip();
                        System.out.println("========conn=======》" + new String(byteBuffer.array()));
                    }
                }
            }
        }
    }
}